package com.demo.SocketServer.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSONObject;
import com.demo.entity.Message;

public class ServerThread extends Thread {

	private Socket socket;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}
	
	private static boolean willCloseSocket = false;

	@Override
	public void run() {
		InputStream request = null;
		InputStreamReader isr = null;
		OutputStream os = null;
		try {
			BIOSocketServer.onlineClinet++;
			// 获取输入流，并读取客户端信息
			request = socket.getInputStream();
			socket.shutdownInput();// 关闭输入流
			// 获取输出流，响应客户端的请求
			os = socket.getOutputStream();
			os.write(doResponse(request));
			os.flush();// 调用flush()方法将缓冲输出
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			try {
				if (os != null)
					os.close();
				if (isr != null)
					isr.close();
				if (request != null)
					request.close();
				if (socket != null && willCloseSocket)
					socket.close();
				BIOSocketServer.onlineClinet--;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private byte[] doResponse(InputStream request) throws IOException{
		String data = IOUtils.toString(request, "UTF-8");
		Message message = (Message) JSONObject.parse(data);
		if(message!=null){
			switch (message.getStatus()) {
			case 1:
				message.getData();
				System.out.println("客户端信息："+data);
				break;
			case 2:
				willCloseSocket = true;
				break;
			default:
				break;
			}
		}
		
		JSONObject retMsg = new JSONObject();
		retMsg.put("success", true);
		retMsg.put("onlineClientNum", BIOSocketServer.onlineClinet);
		retMsg.put("historyClientNum", BIOSocketServer.clinetCount);
		InetAddress address = socket.getInetAddress();
		retMsg.put("clientIP", address.getHostAddress());
		return retMsg.toJSONString().getBytes();
	}

}
